﻿package com.thaiflashdev.utils 
{
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	/**
	 * ...
	 * @author kabuto.boy
	 */
	public class KeyObject
	{
		private var _stage:Stage;
		private var _pressingKey:int = 0;
		private var _lastPressingKey:int = 0;
		private var _pressing:Boolean = false;
		
		public function KeyObject($stage:Stage) 
		{
			_stage = $stage;
			_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
		}
		public static function initClass($stage:Stage):KeyObject 
		{
			return new KeyObject($stage);
		}
		public static function getListenerInstance($stage:Stage):KeyObject 
		{
			return initClass($stage);
		}
		
		private function keyDownHandler(e:KeyboardEvent):void 
		{
			_pressing = true;
			_lastPressingKey = (_pressingKey != _lastPressingKey)?_pressingKey:_lastPressingKey;
			_pressingKey = e.keyCode;
		}
		private function keyUpHandler(e:KeyboardEvent):void 
		{
			_pressing = false;
			_lastPressingKey = (_pressingKey != _lastPressingKey)?_pressingKey:_lastPressingKey;
			_pressingKey = 0;
		}
		
		public function isDown($keyCode:int):Boolean 
		{
			return Boolean(_pressingKey == $keyCode);
		}
		
		public function get pressing():Boolean { return _pressing; }
		public function get pressingKey():int { return _pressingKey; }
		//public function get lastPressingKey():int { return _lastPressingKey; }
		
	}

}